package com.cloud.configure;

import com.cloud.message.AbstractSocketConsumer;
import com.cloud.socket.SocketConsumer;
import jakarta.annotation.PostConstruct;
import org.apache.commons.lang3.ObjectUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.socket.server.standard.ServerEndpointExporter;

import java.util.Map;

@Configuration
public class WebSocketConfiguration implements ApplicationContextAware {

    private static Logger logger = LoggerFactory.getLogger(WebSocketConfiguration.class);

    private ConfigurableApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = (ConfigurableApplicationContext) applicationContext;
    }

    /**
     * 注入ServerEndpointExporter，
     * 这个bean会自动注册使用了@ServerEndpoint注解声明的Websocket endpoint
     */
    @Bean
    public ServerEndpointExporter serverEndpointExporter() {
        return new ServerEndpointExporter();
    }

    @PostConstruct
    public void socketConsumer() {
        Map<String, Object> consumerBeans = applicationContext.getBeansWithAnnotation(SocketConsumer.class);
        if (ObjectUtils.isNotEmpty(consumerBeans)) {
            for (Map.Entry<String, Object> entry : consumerBeans.entrySet()) {
                loadSocketConsumer(entry.getKey(), entry.getValue());
            }
        }
    }

    private void loadSocketConsumer(String beanName, Object bean) {
        try {
            SocketConsumer QTConsumer = applicationContext.findAnnotationOnBean(beanName, SocketConsumer.class);
            AbstractSocketConsumer socketConsumer = (AbstractSocketConsumer) bean;
            socketConsumer.InItSocketClient(QTConsumer.socketHost(), QTConsumer.socketCode());
            logger.info(beanName + "/Socket客户端:{},开始", QTConsumer.socketCode());
        } catch (Exception e) {
            logger.error(beanName + "/Socket客户端:{},失败", e);
        }
    }

}

